package cn.edu.nhic.controller;

import cn.edu.nhic.constant.Constants;
import cn.edu.nhic.dao.UserDao;
import cn.edu.nhic.entity.User;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Description
 * @Date 2024/9/14 19:05
 * @Created by dwp
 */
@WebServlet(urlPatterns = "/register_servlet")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 1. 获取参数
         * 2. 校验参数
         * 3. 写数据库
         * 4. 返回跳转登录界面
         */
        String userName = req.getParameter(Constants.ParamsKeyEnum.USER_NAME_KEY.getParamKey());
        String password = req.getParameter(Constants.ParamsKeyEnum.PASSWORD_KEY.getParamKey());
        String tel = req.getParameter(Constants.ParamsKeyEnum.TEL_KEY.getParamKey());
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(password) ||StringUtils.isBlank(tel)) {
            processErrorInfo(req, resp);
            return;
        }

        String age = req.getParameter(Constants.ParamsKeyEnum.AGW_KEY.getParamKey());
        String[] favor = req.getParameterMap().getOrDefault(Constants.ParamsKeyEnum.FAVOR_KEY.getParamKey(), new String[]{});
        String sex = req.getParameter(Constants.ParamsKeyEnum.SEX_KEY.getParamKey());

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        user.setTel(tel);
        if (StringUtils.isNotBlank(age)) {
            user.setAge(Integer.valueOf(age));
        }

        user.setSex(sex);
        if (favor != null && favor.length > 0) {
            user.setFavor(Arrays.stream(favor).collect(Collectors.toList()));
        }

        UserDao userDao = UserDao.getUserDao();
        boolean insertUser = userDao.insertUserDao(user);
        if (insertUser) {
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        } else {
            processErrorInfo(req, resp);
        }


    }

    private void processErrorInfo(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException{
        response.setContentType(Constants.DOC_FORMAT_TYPE);
        response.setCharacterEncoding(Constants.CharSetEnum.UTF_8.getCharSet());
        String res = "<h2> 用户名或密码或电话不能为空 </h2>";
        PrintWriter writer = response.getWriter();
        writer.print(res);

        writer.flush();
        writer.close();
        // todo: test include
        request.getRequestDispatcher("register.jsp").include(request, response);
    }
}
